<?php
/**
 * Created by PhpStorm.
 * User: this
 * Date: 2018/12/12
 * Time: 10:21
 */

namespace app\admin\controller;

use think\Controller;
use app\admin\model\Set;
use think\Db;
use think\Session;
use app\admin\model\User;

class Setting extends Controller{
    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index(){
        $model = new Set();
        $condition['setting_type'] = ['in','input,textarea'];
        $info = $model->getList($condition);
        foreach ($info as &$v){
            if($v['setting_type'] == 'input') {
                $v['html'] = '<input name="' . $v['setting_cod'] . '" value="' . $v['setting_value'] . '" class="common-text required" size="50" type="text">';
            }else if($v['setting_type'] == 'textarea'){
                $v['html'] = '<textarea name="'.$v['setting_cod'].'" class="common-textarea" style="width:44%;margin-top: 1%;" rows="5" >'.$v['setting_value'].'</textarea>';
            }else{
                $v['html'] = '';
            }
        }
        $this->assign('info',$info);
        $this->assign('site_title','系统设置-管理后台-百步园艺');
        $this->assign('url','/baibu/admin/Setting/edit');
        return $this->fetch('index');
    }

    public function edit(){
        if(!request()->isPost()){
            ajaxReturn(0,'参数错误!',0);
        }
        $data = input('post.');
        $num = 0;
        foreach ($data as $k => $v){
            $condition['setting_cod'] = $k;
            $update['setting_value'] = $v;
            if($k == 'telephone'){
                if(!preg_match('/1[3456789]\d{9}/',$v)){
                    ajaxReturn(0,'手机格式不正确!',0);
                }
            }
            Db::startTrans();
            try{
                Db::name('setting')->where($condition)->update($update);
                Db::commit();
                $num +=1;
            }catch (\Exception $e){
                Db::rollback();
                ajaxReturn(0,$e->getMessage(),0);
            }
        }
        if($num == count($data)){
            ajaxReturn('/baibu/admin/Setting','保存成功!',1);
        }else{
            ajaxReturn(0,'保存失败!',0);
        }
    }
    public function editPwd(){
        if(request()->isPost()){
            $data = input('post.');
            if(!isset($data['password']) || !$data['password']){
               ajaxReturn(0,'第一次密码不能为空!',0);
            }
            if(!isset($data['password2']) || !$data['password2']){
                ajaxReturn(0,'第二次密码不能为空!',0);
            }
            if($data['password'] != $data['password2']){
                ajaxReturn(0,'两次密码不一致',0);
            }
            if(strlen($data['password']) < 6 || strlen($data['password2']) < 6){
                ajaxReturn(0,'密码长度必须大于6个字符',0);
            }
            $user_id = Session::get('user_id');
            $update['user_salt'] = makeSalt();
            $update['user_password'] = md5(md5($data['password'].$update['user_salt']));
            $model = new User();
            $result = $model->edit(array('user_id'=>$user_id),$update);
            if($result){
                Session::delete('username');
                Session::delete('remark');
                Session::delete('user_id');
                ajaxReturn('/baibu/admin/Login','修改成功!',1);
            }else{
                ajaxReturn(0,'修改失败!',0);
            }

        }
        $this->assign('nav','修改密码');
        $this->assign('site_title','修改密码-管理后台-百步园艺');
        $this->assign('url','/baibu/admin/Setting/editPwd');
        return $this->fetch('edit');
    }

    public function img(){
        $img = Db::name('setting')->field('setting_title,setting_id,setting_value,setting_cod')->where(array('setting_cod'=>array('in','logo,company_img')))->select();
        $info = [];
        $arr = [];
        foreach ($img as $v){
            $info[$v['setting_cod']] = $v['setting_value'];
            $arr[$v['setting_cod']] = $v['setting_id'];
        }
        if($_FILES){
            $one = true;
            $two = true;
            if(isset($_FILES['company_img']) && $_FILES['company_img']['name']){
                $files = request()->file('company_img');
                $image_info = $files->getInfo();
                $file_ext = strrchr($image_info['name'],'.');
                $type = array('.jpg','.png','.gif','jpeg','.JPG','.PNG','.GIF','.JPEG');
                if(in_array($file_ext,$type)){
                    $path = 'public/static/image/company/';
                    $result = $files->move(ROOT_PATH.$path);
                    if($result){
                        $data['setting_value'] = '/baibu/'.$path.$result->getSaveName();
                        if(isset($info['company_img'])){
                            del_file(substr(ROOT_PATH,0,-7).$info['company_img']);
                        }
                        $rs = Db::name('setting')->where(array('setting_id'=>$arr['company_img']))->update($data);
                        if(!$rs){
                            $one = false;
                        }
                    }else{
                        $one = false;
                    }
                }else{
                    $one = false;
                }
            }
            if(isset($_FILES['logo']) && $_FILES['logo']['name']){
                $files = request()->file('logo');
                $image_info = $files->getInfo();
                $file_ext = strrchr($image_info['name'],'.');
                $type = array('.jpg','.png','.gif','jpeg','.JPG','.PNG','.GIF','.JPEG');
                if(in_array($file_ext,$type)){
                    $path = 'public/static/image/logo/';
                    $result = $files->move(ROOT_PATH.$path);
                    if($result){
                        $data['setting_value'] = '/baibu/'.$path.$result->getSaveName();
                        if(isset($info['logo'])){
                            del_file(substr(ROOT_PATH,0,-7).$info['logo']);
                        }
                        $rs = Db::name('setting')->where(array('setting_id'=>$arr['logo']))->update($data);
                        if(!$rs){
                            $two = false;
                        }
                    }else{
                        $two = false;
                    }
                }else{
                    $two = false;
                }
            }
            if($one && $two){
                ajaxReturn(1,'修改成功！',1);
            }else{
                ajaxReturn(0,'修改失败！',0);
            }
        }
        $this->assign('url','/baibu/admin/Setting/img');
        $this->assign('info',$info);
        $this->assign('nav','图片管理');
        $this->assign('site_title','图片管理-管理后台-百步园艺');
        return $this->fetch('img');
    }

    /**
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function banner(){
        $model = new Set();
        $banner_info = $model->getOne(array('setting_cod'=>'banner_img'),'setting_value');
        $banner = unserialize($banner_info['setting_value']);
        $this->assign('banner',$banner);
        $this->assign('site_title','轮播图-管理后台-百步园艺');
        return $this->fetch('banner');
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function banner_del(){
        if(!$_GET){
            ajaxReturn(0,'参数错误!',-1);
        }
        $model = new Set();
        $banner_info = $model->getOne(array('setting_cod'=>'banner_img'),'setting_value');
        $banner = unserialize($banner_info['setting_value']);
        $result = false;
        if(gettype($_GET['banner_id']) == 'array'){
            foreach ($_GET['banner_id'] as $k => $v){
                if(in_array($v,array_keys($banner))){
                    del_file(substr(ROOT_PATH,0,-7).$banner[$v]['img']);
                    unset($banner[$v]);
                    $update['setting_value'] = serialize(array_values($banner));
                    $result = $model->edit(array('setting_cod'=>'banner_img'),$update);
                }
            }
        }else{
            if(in_array($_GET['banner_id'],array_keys($banner))) {
                del_file(substr(ROOT_PATH,0,-7).$banner[$_GET['banner_id']]['img']);
                unset($banner[$_GET['banner_id']]);
                $update['setting_value'] = serialize(array_values($banner));
                $result = $model->edit(array('setting_cod'=>'banner_img'),$update);
            }
        }
        if($result){
            ajaxReturn($_GET['banner_id'],'删除成功!',1);
        }else{
            ajaxReturn(0,'删除失败!',0);
        }
    }
    public function banner_add(){
        $this->assign('url','/baibu/admin/Setting/banner_add');
        $this->assign('info','');
        $this->assign('nav','添加图片');
        $this->assign('site_title','添加图片-管理后台-百步园艺');
        if($_FILES){
            if(!$_FILES['banner']['name']){
                ajaxReturn(0,'图片不能为空！',0);
            }
            $model = new Set();
            $banner_info = $model->getOne(array('setting_cod'=>'banner_img'),'setting_value');
            $update = array();
            $files = request()->file('banner');
            $image_info = $files->getInfo();
            $file_ext = strrchr($image_info['name'],'.');
            $type = array('.jpg','.png','.gif','jpeg','.JPG','.PNG','.GIF','.JPEG');
            if(in_array($file_ext,$type)){
                $path = 'public/static/image/banner/';
                $result = $files->move(ROOT_PATH.$path);
                if($result){
                    $data['img'] = '/baibu/'.$path.$result->getSaveName();
                    if($banner_info['setting_value']){
                        $arr = unserialize($banner_info['setting_value']);
                        $arr[] = $data;
                        $arr = array_values($arr);
                        $update['setting_value'] = serialize($arr);
                    }else{
                        $update['setting_value'] = serialize(array($data));
                    }
                    $res = $model->edit(array('setting_cod'=>'banner_img'),$update);
                    if($res){
                        ajaxReturn('/baibu/admin/Setting/banner','图片上传成功！',1);
                    }else{
                        ajaxReturn(0,'图片上传失败！',0);
                    }
                }else{
                    ajaxReturn(0,'图片上传失败！',0);
                }
            }else{
                ajaxReturn(0,'图片格式不正确！',0);
            }
        }
        return $this->fetch('banner_add');
    }
    public function delCache(){
        try{
            delete_dir_file(ROOT_PATH.'runtime/cache');
            delete_dir_file(ROOT_PATH.'runtime/temp');
            ajaxReturn(1,'缓存清除成功!',1);
        }catch (\Exception $e){
            ajaxReturn(0,$e->getMessage(),0);
        }

    }
}